<template>
    <div class="container" v-if="templateStyle==='level-3'" :class="isUpdate&&'fadeIn'">
        <ul class="option-list">
            <li class="option-item" v-for="(item,index) in wordArr" @click="answerHandler(item,index,item.order)"
                :class="activeIndex===index&&'active'">
                <ul class="text">
                    <li v-if="item.chinese">{{item.chinese}}</li>
                    <li v-else-if="item.pinyin">{{item.pinyin}}</li>
                    <li v-else-if="item.english">{{item.english}}</li>
                </ul>
            </li>
        </ul>
        <div class="match-container">

            <ul class="match-list">
                <li class="match-list-item" v-for="(item,index) in content.bottomSentences">
                    <ul>
                        <li>
                            <loadingImage :src="addPrefixHost(content.images[index])" alt=""
                                          class="match-img"></loadingImage>
                        </li>
                        <li v-html="getHtml(item,index)" @click="clickFn($event)"></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
    <div v-else>
        <div class="coming-soon"></div>
    </div>
</template>
<script>
    import Vue from 'vue';
    import {mapState, mapGetters, mapActions} from 'vuex'
    import Component from 'vue-class-component'
    import R from 'ramda';
    import loadingImage from '~/components/loadingImage'

    @Component({
        components: {loadingImage},
        async fetch({store, params}) {
            await store.dispatch("index/exercise/index/setContentInfo", params);
        },
        computed: {
            wordArr() {
                const wordArr = [];
                if (this.content.words) {
                    for (let i = 0; i < this.content.words.length; i++) {
                        wordArr.push(this.content.words[i]);
                    }
                }
                return wordArr.sort(function () {
                    return Math.random() - 0.5
                });
            },
            ...mapState('index/exercise/index', {
                templateStyle: state => state.templateStyle,
                content: state => state.contentInfo ? state.contentInfo.content : {}
            }),
        },
        methods: {
            ...mapActions('index/exercise/index', [
                'setAnswer','setMyAnswer'
            ])
        },
        watch: {
            content() {
//                当数据发生变化后执行动画效果
                this.isUpdate = true;
                const initData = {
                    activeItem: null,
                    activeIndex: "",
                    answerArr: [],
                    errorMessage: "",
                    correctArr: [],
                };
                const init = (val, key) => {
                    this[key] = val;
                };
                R.forEachObjIndexed(init)(initData);
                this.init();
                setTimeout(_ => {
                    this.isUpdate = false;
                }, 600)
            }
        },
    })
    export default class Sentence extends Vue {
        activeItem = null;
        activeIndex = "";
        answerArr = [];
        isUpdate = false;
        errorMessage = "";
        correctArr = [];
        myAnswer = '';

        answerHandler(item, index, order) {
            this.activeIndex = index;
            this.activeItem = item;
        }

//        checkAnswer() {
//            const answerOrder = R.map(R.ifElse(R.clone, R.prop("order"), R.F))(this.answerArr);
//            const rightOrder = R.map(R.split(","))(this.content.answerOrder);
//            const answer = R.any(R.equals(answerOrder))(rightOrder);
//            this.setAnswer({
//                answer,
//                msg: `　${R.map(item => R.or(R.prop('chinese'), R.prop('english'), R.prop('pinyin'))(R.find(R.propEq('order', item))(this.content.words)))
//                (rightOrder[0])}`
//            });
//        }

        mounted() {
            this.init();
        }

        created() {
//            this.$nextTick(_ => {
//                const pits = document.querySelectorAll(".pit-item");
//                const addEventListener = (event, fn, isPre = false) => {
//                    return (item) => {
//                        item.addEventListener(event, fn, isPre);
//                    }
//                };
//                R.forEach(addEventListener("click", this.clickFn, false))(pits);
//            })

            console.log(this.content)
        }

        init() {
            this.$nextTick(_ => {
                let ele = document.querySelectorAll(".pit-item");
                for (let i = 0; i < ele.length; i++) {
                    Vue.set(this.answerArr, i, "0");
                    Vue.set(this.correctArr, i, "0");
                }
                if (this.content.answerOrder) {
                    for (let i = 0; i < this.content.answerOrder.length; i++) {
                        for (let j = 0; j < this.content.answerOrder[i].split(",").length; j++) {
                            if (this.content.words) {
                                for (let k = 0; k < this.content.words.length; k++) {
                                    if (this.content.words[k].order === this.content.answerOrder[i].split(',')[j]) {
                                        this.errorMessage += (this.content.words[k].chinese || this.content.words[k].english) + "<br>";
                                    }
                                }
                            }
                        }
                    }
                }
                this.setAnswer({
                    answer: false,
                    msg: this.errorMessage
                });
            })
        }


        clickFn(e) {
            this.myAnswer = '';
            if (e.target.nodeName.toUpperCase() === "DIV" && e.target.className === "pit-item") {
                let ele = e.target;
                let eleIndex = ele.getAttribute("data-group");
                if (this.activeItem != null) {
                    if (this.answerArr[eleIndex] === "0") {
                        Vue.set(this.answerArr, eleIndex, this.activeItem);
                        this.wordArr.splice(this.activeIndex, 1);
                        this.activeItem = null;
                        this.activeIndex = null;
                    } else {
                        this.wordArr.splice(this.activeIndex, 1);
                        this.wordArr.push(this.answerArr[eleIndex]);
                        Vue.set(this.answerArr, eleIndex, this.activeItem);
                        this.activeItem = null;
                        this.activeIndex = null;
                    }
                } else {
                    if (this.answerArr[eleIndex] !== "0") {
                        this.wordArr.push(this.answerArr[eleIndex]);
                    }
                    Vue.set(this.answerArr, eleIndex, "0");
                }
                this.Answer(eleIndex);
            }
        }

        Answer(Index) {
            let answer = false;
            if (this.answerArr[Index].order) {
                Vue.set(this.correctArr, Index, this.answerArr[Index].order);
            } else {
                Vue.set(this.correctArr, Index, "0");
            }
            for (let i = 0; i < this.content.answerOrder.length; i++) {
                if (this.correctArr.toString() === this.content.answerOrder[i]) {
                    answer = true;
                }
            }
            this.setAnswer({
                answer: answer,
                msg: this.errorMessage
            });
            console.log(this.answerArr);
            for(let i=0;i<this.answerArr.length;i++){
                if(this.answerArr[i]!== "0"){
//                    i<this.answerArr.length-1?this.myAnswer += (this.answerArr[i].chinese||this.answerArr[i].chinese) +',':this.myAnswer += (this.answerArr[i].chinese||this.answerArr[i].chinese);
                    i<this.answerArr.length-1?this.myAnswer += (this.answerArr[i].chinese||this.answerArr[i].chinese) +',':this.myAnswer += (this.answerArr[i].chinese||this.answerArr[i].chinese);
                }
            }
            this.setMyAnswer(this.myAnswer);
        }

//        getHtml(sen, index) {
//            const indexArr = R.match(/\[.+[\]、]/g, sen);
//            indexArr.forEach((item) => {
//                sen = sen.replace(/\[.+[\]、]/, `<div data-group="${index}" class='pit-item'></div>`)
//            });
//            return sen;
//        }
        getHtml(item, index) {
            let obj = item;
            if (obj && obj.length) {
                const re = /([^\[\]]+)(?=\])/g;
                let arr = obj.match(re);
                if (arr) {
                    for (let i = 0; i < arr.length; i++) {
                        if (arr[i] % arr[i] === 0) {
                            let key = this.answerArr[arr[i] - 1] || '';
                            obj = obj.replace(/\[.]、?/, "<div class='pit-item' data-group='" + (arr[i] - 1) + "'>" + (key.chinese || key.english || '') + "</div>");
                        }
                    }
                }
                return obj;
            }
        }
    }
</script>
<style lang="scss">
    .match-list-item {
        .pit-item {
            min-width: 100px;
            height: 60px;
            display: inline-block;
            padding: 0 10px;
            line-height: 60px;
            font-size: 24px;
            text-align: center;
            cursor: pointer;
            background: url("~~assets/img/main_content/exercise/pit2-active.png") no-repeat;
            background-size: 100% 100%;
            vertical-align: middle;
        }
    }
</style>
<style lang="scss" scoped>
    @import "~~assets/sass/mixins";
    @import "~~assets/sass/functions";

    .coming-soon {
        width: 600px;
        height: 236px;
        margin: 100px auto auto auto;
        background: url(~~assets/img/exercise/coming.png) no-repeat;
        background-size: 100% 100%;
    }

    .fadeIn {
        animation: fadeIn .4s ease-in;
        transform: translateZ(0);
    }

    @keyframes fadeIn {
        from {
            transform-origin: left;
            transform: scaleX(.4);
            opacity: 0;
        }
    }

    .container {
        text-align: center;
        margin-top: 40px;
        .option-list {
            display: inline-block;
            vertical-align: middle;
            min-width: 125px;

            .option-item {
                @include fullBgWithMainContentPicName("content-button.png");
                min-width: 1.23rem;
                line-height: .6rem;
                font-size: 22px;
                cursor: pointer;
                &.active {
                    transition: all .1s ease-in;
                    @include fullBgWithMainContentPicName("button-yellow-active.png");
                }
                &:not(:first-child) {
                    margin-top: 30px;
                }
                .text {
                    vertical-align: middle;
                    line-height: 1;
                    display: inline-block;
                    li:not(:first-child) {
                        margin-top: 5px;
                    }
                }
            }
        }
        .match-container {
            display: inline-block;
            vertical-align: middle;
            margin-left: 20px;
            .match-list {
                font-size: 26px;
                .match-img {
                    width: 2.2rem;
                    height: 1.7rem;
                    border-radius: 5px;
                }
                .match-list-item {
                    display: inline-block;
                    margin: 0 20px;
                }

                li {
                    margin-top: 30px;
                }
            }
        }
    }
</style>